package com.reactim.common.util;

import java.time.Instant;
import java.util.concurrent.ThreadLocalRandom;

/**
 * ID生成器工具类
 * 生成分布式唯一ID
 */
public class IdGenerator {
    
    private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final int BASE = ALPHABET.length();
    
    /**
     * 生成消息ID
     * 格式: msg_timestamp_random
     */
    public static String generateMessageId() {
        long timestamp = Instant.now().toEpochMilli();
        String randomPart = generateRandomString(8);
        return "msg_" + timestamp + "_" + randomPart;
    }
    
    /**
     * 生成用户ID
     */
    public static long generateUserId() {
        return generateSnowflakeId();
    }
    
    /**
     * 生成群组ID
     */
    public static long generateGroupId() {
        return generateSnowflakeId();
    }
    
    /**
     * 生成随机字符串
     */
    public static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        ThreadLocalRandom random = ThreadLocalRandom.current();
        
        for (int i = 0; i < length; i++) {
            sb.append(ALPHABET.charAt(random.nextInt(BASE)));
        }
        
        return sb.toString();
    }
    
    /**
     * 简化版雪花算法生成ID
     */
    private static long generateSnowflakeId() {
        long timestamp = Instant.now().toEpochMilli();
        long random = ThreadLocalRandom.current().nextLong(0, 4096); // 12位随机数
        
        // 时间戳左移12位 + 随机数
        return (timestamp << 12) | random;
    }
}